import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from './store'
//引入异步路由
import {asyncRouters} from '@/router'
const whiteList =  ['/login','/404']
router.beforeEach(async(to, from, next) =>{
  NProgress.start();
  if(store.getters.token) {
    if(to.path == '/login') {
     
      next('/')
      NProgress.done()
    }else {
      if(!store.getters.userId) {
        const {roles} = await store.dispatch('getUserInfo')
       
        //过滤路由
        const filterRouter = asyncRouters.filter(item=>{
          return roles.menus.includes(item.name)
        })
      
        //追加路由
         router.addRoutes([...filterRouter, { path: "*", redirect: "/404", hidden: true },])
         next(to.path) //给路由转发
          //调用仓库方法合并路由
       store.commit('MERGE_ROUTES',filterRouter)
      }
     else {
      next()
     }
    }
  }else {
    if(whiteList.indexOf(to.path) != -1) {
      next()
    }else {
      next('/login')
      NProgress.done()
    }
  }
})


router.afterEach(()=>{
  NProgress.done();
})